package com.longyiqun.apitest.nouse;

import com.google.gson.Gson;
import com.longyiqun.apitest.BussinessUtil;
import org.apache.http.util.TextUtils;

import java.util.HashMap;

/**
 * Created by testypp on 2017/6/29.
 */

public class RequestParam {

    private HashMap<String, String> params = new HashMap<>();

    public RequestParam() {
        params.put("timespan", String.valueOf(System.currentTimeMillis()));
        params.put("platform", "android");
        params.put("sys_version", "200");
        params.put("soft_version", "200");
        params.put("device_model", "device_model");
        params.put("screen", "screen");
    }

    private void putParam(String key, String value) {
        params.put(key, value);
    }

    public String getMethod() {
        return params.get("method");
    }

    public HashMap<String, String> getParams() {
        return params;
    }

    public static final class Builder {

        private HashMap<String, Object> methodParams = new HashMap<>();
        private String method;

        public Builder() {
            methodParams.put("platform", "android");
            methodParams.put("market_channel", "YPP");
            methodParams.put("access_token", "");
            methodParams.put("token", "");
            methodParams.put("v_num", 60);
            methodParams.put("udid", "1234567890");
        }

        public Builder setMethod(String method) {
            this.method = method;
            return this;
        }


        public Builder putParam(String key, Object value) {
            methodParams.put(key, value);
            return this;
        }

        public Builder putParamAll(HashMap<String, String> params) {
            if (params != null)
                methodParams.putAll(params);
            return this;
        }


        public RequestParam build() {
            String methodStr = new Gson().toJson(methodParams);
            byte[] requestBytes = methodStr.getBytes();
            String requestString = Base64.encode(requestBytes);

            RequestParam requestParam = new RequestParam();
            if (!TextUtils.isEmpty(method)) {
                requestParam.putParam("method", method);
            }

            requestParam.putParam("request", requestString);
            String signature = BussinessUtil.getRequestSignature(requestParam.getParams());
            requestParam.putParam(signature, signature);
            return requestParam;
        }
    }

}